<template>
	<view class="tabs">

		<scroll-view style="width:100wh;" class="scroll-h" :scroll-x="true" :scroll-with-animation="true"   :show-scrollbar="false" :scroll-into-view="scrollInto" >
			<view class="flex-row">
					<view
					 v-for="(tab, index) in tabBars"
					 :key="tab.id" class="uni-tab-item flex-row"
					 :id="'tabs-id-' + index"
					  :data-current="index" @click="ontabtap" 	>
						<text class="uni-tab-item-title" :class="isScroll(index) ? 'uni-tab-item-title-active' : ''">{{ tab.name }}</text>
						<!-- 下划线 -->
						<!-- <view style="width:100%" :class="isScroll(index) ? 'underlinebox' : 'underlinebox-active'"><view class="underline"></view></view> -->
					</view>
			</view>
		</scroll-view>


		<swiper :current="tabIndex"   :style="{height:swiperHeight+'px'}"  class="swiper-box wrap-swiper"  style="flex: 1;"  :duration="300" @change="ontabchange">
			<swiper-item class="swiper-item" v-for="(tab, index1) in goodsList" :key="index1">
				<!-- #ifdef APP-NVUE -->
				<list class="scroll-v list" :class="'list'+index1" :id="'list'+index1" enableBackToTop="true" scroll-y loadmoreoffset="15" @loadmore="loadMore(index1)">
					<refresh class="refresh" @refresh="onrefresh(index1)" @pullingdown="onpullingdown" :display="tab.refreshing ? 'show' : 'hide'">
						<div class="refresh-view">
							<image
								class="refresh-icon"
								:src="refreshIcon"
								:style="{ width: tab.refreshing || pulling ? 0 : '30px' }"
								:class="{ 'refresh-icon-active': tab.refreshFlag }"
							></image>
							<loading-indicator class="loading-icon" animating="true" v-if="tab.refreshing"></loading-indicator>
							<text class="loading-text">{{ tab.refreshText }}</text>
						</div>
					</refresh>
					 <goodslist class="margin-t12" :sortType= :list="tab.data" :cols="3"></goodslist>

					<cell class="loading-more" v-if="tab.isLoading || tab.data.length > 4">
						<text class="loading-more-text"  @tap="loadMore(index1)">{{ tab.loadingText }}</text>
					</cell>
				</list>
				<!-- #endif -->
				<!-- #ifndef APP-NVUE -->
				<scroll-view class="scroll-v list"  :id="'list'+index1" enableBackToTop="true" scroll-y="true" @scrolltolower="loadMore(index1)">
				     <view style="height:60vh" :class="'list'+index1">
						 <goodslist class="margin-t12" :sortType="3" :list="tab.data" :cols="3"></goodslist>
						<!-- <view v-for="(goodsitem, index2) in tab.data" :key="index2">
						</view> -->
						<view class="loading-more" v-if="tab.isLoading || tab.data.length > 4">
							<text class="loading-more-text"  @tap="loadMore(index1)">{{ tab.loadingText }}</text>
						</view>
						</view>
				</scroll-view>
				<!-- #endif -->
			</swiper-item>
		</swiper>


	</view>
</template>
<script>
import goodItem from './goods-item.nvue';
// import uniIcons from '@/components/uni-icons/uni-icons.vue';

const API = require('@/utils/api/shops.js').default;
const $ = require('@/utils/api.js');
let self;

// 缓存每页最多
const MAX_CACHE_DATA = 100;
// 缓存页签数量
const MAX_CACHE_PAGE = 3;

export default {
	components: {
		goodItem,
		// uniIcons
	},
	data() {
		return {

			 //滑块的高度(单位px)
			      swiperHeight: 0,
				  listHeight:0,
			      // //当前索引
			      // currentIndex: 0,
			      // //列表数据
			      // dataList: [],

			goodsList: [],
			cacheTab: [],
			tabIndex: 0,
			lastIndex: 0, //上一次的坐标
			tabBars: [
			],
			scrollInto: '',
			showTips: false,
			navigateFlag: false,
			pulling: false,


			list: [],
			page: 1,
			pageSize: 20,
			totalPage: 1,
			title: '',
			shopId: '',
			catePid: '',
			cateTid: '',
			cateId: '',
			shopCateId: '',
			type: '',
			sort: '',



			refreshIcon:
				''
		};
	},
	created() {
	// mounted() {
	    let _this = this
		this.initData()

	},
	onReachBottom(e) {
		setTimeout(() => {
			this.getList(this.tabIndex);
		}, 500);
	},
	methods: {
		isScroll(index) {
			return this.tabIndex == index;
		},
		//新闻详情
		goDetail(item, index) {
			let data = {
				id: index,
				title: item.title,
				author: '详情',
				time: item.datetime
			};
			let url = item.isVideo == true ? 'videoDetails' : 'details';
			uni.navigateTo({
				url: `/pages/details/${url}?data=${JSON.stringify(data)}`
			});
		},
		// getList(index) {

		// 	// console.log("activeTab.index ",index )
		// 	// 	console.log(" Math.floor(Math.random() * 5)", Math.floor(Math.random() * 5) )

		// 	 Math.floor(Math.random() * 5)
		// 	let activeTab = this.goodsList[index];
		// 	let list = [];
		// 	for (let i = 1; i <= 10; i++) {
		// 		let item = Object.assign({}, newsData['data' + Math.floor(Math.random() * 5)]);
		// 		item.id = this.newGuid();
		// 		list.push(item);
		// 	}



		// 	activeTab.data = activeTab.data.concat(list);
		// 	console.log("activeTab.data ",activeTab.data )
		// },

		initData(){
			let _this = this
			this.geCateList();
			this.$nextTick(() => {
				setTimeout(() => {
						// 动态设置 swiper 的高度
						let index = 0;
						let list = "#list"+index;
						_this.getlistHeight(list);
				}, 100);
			});

		},
		 geCateList() {
			let _this = this
			$.ajax({
				url: API.goodsCateApi,
				data: {
				},
				method: 'GET',
				success(res) {
					_this.tabBars = res.data

					_this.tabBars.forEach(tabBar => {
						_this.goodsList.push({
							data: [],
							page: 0,
							isLoading: false,
							refreshText: '',
							loadingText: '加载更多...'
						});
					});

					let index;
					index = 0;
						console.log("_this.goodsList[index]"+index,	_this.goodsList[index])
					_this.getList(index);
				}
			})
			 // console.log("tabBars",_this.tabBars)
		},
		 getList(index) {
			let _this = this
			let  cateId = _this.tabBars[index].id
			// cateId = 77

			let  page  = this.goodsList[index].page ;
			page++;

			// console.log('page',page)
			// page = 1;
						// console.log("_this.goodsList[index]"+index,	_this.goodsList[index])
			 this.$http
				.get(API.searchGoodsApi, {cateId:cateId,page:page})
				.then(async res => {
					let list = res.data.list;
					_this.goodsList[index].page =res.data.pageNum
					// console.log('_this.goodsList[index].data',_this.goodsList[index].data)
					_this.goodsList[index].data = [..._this.goodsList[index].data, ...list];


					// let activeTab  = _this.goodsList[index];
			     	// activeTab.data = activeTab.data.concat(list);
					console.log("_this.goodsList[index]"+index,	_this.goodsList[index])
					// _this.goodsList[index].data  = activeTab
					// _this.$set(_this.goodsList,index,activeTab)

					_this.$nextTick(() => {
						setTimeout(() => {
								// 动态设置 swiper 的高度
								let index = 0;
								let list = "#list"+index;
								_this.getlistHeight(list);
						}, 100);
					});

				})
				.catch((e) => {
					console.log(e);
					console.log("eeeeeeeeeeeeeeeeeeee");
				});

		},
		close(index1, index2) {
			uni.showModal({
				content: '是否删除本条信息？',
				success: res => {
					if (res.confirm) {
						this.goodsList[index1].data.splice(index2, 1);
					}
				}
			});
		},

		loadMore(e) {
			console.log(e)
			console.log("loadMoreloadMoreloadMoreloadMoreloadMore")
			setTimeout(() => {
				this.getList(this.tabIndex);
			}, 500);
		},
		ontabtap(e) {
			let index = e.target.dataset.current || e.currentTarget.dataset.current;
			this.isLeft = this.switchTab(index);


			var nextIndex = index - 2;
			nextIndex = nextIndex <= 0 ? 0 : nextIndex;
			this.scrollInto = 'tabs-id-' + nextIndex
		},

		//手动切换题目
		changeSwiper(e) {
		  this.currentIndex = e.detail.current;
		  //动态设置swiper的高度，使用nextTick延时设置
		  this.$nextTick(() => {
			this.setSwiperHeight();
		  });
		},
		//动态设置swiper的高度
		// setSwiperHeight() {
		//   let element = "#content-wrap" + this.currentIndex;
		//   let query = uni.createSelectorQuery().in(this);
		//   query.select(element).boundingClientRect();
		//   query.exec((res) => {
		// 	if (res && res[0]) {
		// 	  this.swiperHeight = res[0].height;
		// 	}
		//   });
		// },
		getlistHeight(list){
			let _this = this
			  let query = uni.createSelectorQuery().in(this);
			  query.select(list).boundingClientRect();
			  query.exec((res) => {
				if (res && res[0]) {
				  this.swiperHeight = res[0].height;
				}
			  });

		},
		getHeight(){
			let _this = this;
			_this.swiperHeight = _this.listHeight;
			return _this.swiperHeight;
		},


		ontabchange(e) {
			let _this = this
			let index = e.target.current || e.detail.current;
			// _this.switchTab(index);

			_this.$nextTick(() => {
				setTimeout(() => {
						// 动态设置 swiper 的高度
						let index = 0;
						let list = "#list"+index;
						_this.getlistHeight(list);
				}, 100);
			});

		},
		switchTab(index) {
			if (this.goodsList[index].data.length === 0) {
				this.getList(index);
			}

			if (this.tabIndex === index) {
				return;
			}

			// 缓存 tabId
			if (this.goodsList[this.tabIndex].data.length > MAX_CACHE_DATA) {
				let isExist = this.cacheTab.indexOf(this.tabIndex);
				if (isExist < 0) {
					this.cacheTab.push(this.tabIndex);
					//console.log("cache index:: " + this.tabIndex);
				}
			}
			this.tabIndex = index;

			if (this.tabIndex < 5 && this.lastIndex < this.tabIndex) {
				this.lastIndex = this.tabIndex;
				return;
			} else if (index >= 5) {
				this.scrollInto = this.tabBars[index - 5].id;
			}
			// this.scrollInto = 'tabs-id-' + index
			this.lastIndex = this.tabIndex;
			// 释放 tabId
			if (this.cacheTab.length > MAX_CACHE_PAGE) {
				let cacheIndex = this.cacheTab[0];
				this.clearTabData(cacheIndex);
				this.cacheTab.splice(0, 1);
				//console.log("remove cache index:: " + cacheIndex);
			}
		},
		clearTabData(e) {
			this.goodsList[e].data.length = 0;
			this.goodsList[e].loadingText = '加载更多...';
		},
		refreshData() {},
		onrefresh(e) {
			var tab = this.goodsList[this.tabIndex];
			if (!tab.refreshFlag) {
				return;
			}
			tab.refreshing = true;
			tab.refreshText = '正在刷新...';

			setTimeout(() => {
				this.refreshData();
				this.pulling = true;
				tab.refreshing = false;
				tab.refreshFlag = false;
				tab.refreshText = '已刷新';
				setTimeout(() => {
					// TODO fix ios和Android 动画时间相反问题
					this.pulling = false;
				}, 500);
			}, 2000);
		},
		onpullingdown(e) {
			var tab = this.goodsList[this.tabIndex];
			if (tab.refreshing || this.pulling) {
				return;
			}
			if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
				tab.refreshFlag = true;
				tab.refreshText = '释放立即刷新';
			} else {
				tab.refreshFlag = false;
				tab.refreshText = '下拉可以刷新';
			}
		},
		newGuid() {
			let s4 = function() {
				return ((65536 * (1 + Math.random())) | 0).toString(16).substring(1);
			};
			return (s4() + s4() + '-' + s4() + '-4' + s4().substr(0, 3) + '-' + s4() + '-' + s4() + s4() + s4()).toUpperCase();
		}
	}
};
</script>



<style>
.imgplay {
	text-align: center;
	width: 40px;
}
.imgplay .icon {
	color: #ffffff;
	font-size: 120rpx;
}
/* 头条小程序组件内不能引入字体 */
/* #ifdef MP-TOUTIAO */
@font-face {
	font-family: uniicons;
	font-weight: normal;
	font-style: normal;
	src: url('~@/static/uni.ttf') format('truetype');
}
/* #endif */

/* 顶部标题栏 */
.page-header {
	background-color: #ec706b;
}
.page-header-wrapper {
	flex-direction: row;
	justify-content: center;
	align-items: center;
	/* #ifdef APP-PLUS */
	height: var(--status-bar-height);
	/* #endif */
	padding: 20upx 10upx 15upx 10upx;
	/* background-color: #ec706b; */
	/* margin-top: 30px; */
}

.page-header-left {
	opacity: 0.9;
	float: left;
	padding-top: 20px;
}

.page-header-center {
	flex: 1;
	padding: 0px 30px 0 20px;
	text-align: center;
}

.search-input {
	height: 40px;
	font-size: 14px;
	color: #999999;
	text-align: center;
	line-height: 70upx;
	border-radius: 100px;
	background-color: #fff;
	padding-top: 10upx;
	padding-bottom: 10upx;
	margin-top: 60upx;
}

.page-header-right {
	width: 63upx;
	align-items: center;
	float: right;
	padding-top: 60upx;
}

.contribute-text {
	font-size: 32upx;
	color: #fff;
}

/* #ifndef APP-PLUS */
page {
	width: 100%;
	min-height: 100%;
	/* display: flex; */
}

/* #endif */

.tabs {
	flex: 1;
	flex-direction: column;
	overflow: hidden;
	background-color: #ffffff;
	/* #ifdef MP-ALIPAY || MP-BAIDU */
	height: 100vh;
	/* #endif */
}

.scroll-h {
	padding-right:20rpx;
	 background-image: linear-gradient(0deg, #ffffff45 0%, #ffeb3b45 100%);
	width: 750rpx;
	height: 80rpx;
	flex-direction: row;
	border-radius:  20rpx 20rpx 0 0;
	/* #ifndef APP-PLUS */
	white-space: nowrap;
	/* #endif */
	/* flex-wrap: nowrap; */
	/* border-color: #cccccc;
		border-bottom-style: solid;
		border-bottom-width: 1px; */
}

.line-h {
	height: 1rpx;
	background-color: #cccccc;
}

.uni-tab-item {
	flex:1;
	display: inline-block;
	flex-wrap: nowrap;
	padding-left: 34rpx;
	padding-right: 34rpx;
}

.uni-tab-item-title {
	color: #000;
	font-size: 30rpx;
	height: 80rpx;
	line-height: 80rpx;
	flex-wrap: nowrap;
	white-space: nowrap;
}

.uni-tab-item-title-active {
	color: #000;
	border-bottom:3px solid #FFEB3B
}



/* .underlinebox {
	height: 3px;
	display: flex;
	align-content: center;
	justify-content: center;
	transition: 0.5s;
	height: 4px;
	background-color: #FFEB3B;
	margin-top: -10px;
} */
.underlinebox-active {
	background-color: none;
}
.swiper-box {
	flex: 1;
}

.swiper-item {
	flex: 1;
	flex-direction: row;
}

.scroll-v {
	flex: 1;
	/* #ifndef MP-ALIPAY */
	flex-direction: column;
	/* #endif */
	width: 750rpx;
}

.update-tips {
	position: absolute;
	left: 0;
	top: 41px;
	right: 0;
	padding-top: 5px;
	padding-bottom: 5px;
	background-color: #fddd9b;
	align-items: center;
	justify-content: center;
	text-align: center;
}

.update-tips-text {
	font-size: 14px;
	color: #ffffff;
}

.refresh {
	width: 750rpx;
	height: 64px;
	justify-content: center;
}

.refresh-view {
	flex-direction: row;
	flex-wrap: nowrap;
	align-items: center;
	justify-content: center;
}

.refresh-icon {
	width: 30px;
	height: 30px;
	transition-duration: 0.5s;
	transition-property: transform;
	transform: rotate(0deg);
	transform-origin: 15px 15px;
}

.refresh-icon-active {
	transform: rotate(180deg);
}

.loading-icon {
	width: 20px;
	height: 20px;
	margin-right: 5px;
	color: #999999;
}

.loading-text {
	margin-left: 2px;
	font-size: 16px;
	color: #999999;
}

.loading-more {
	align-items: center;
	justify-content: center;
	padding-top: 10px;
	padding-bottom: 10px;
	text-align: center;
}

.loading-more-text {
	font-size: 28rpx;
	color: #999;
}
</style>


